#! /bin/bash -
### BEGIN INIT INFO
# Provides:          pffs
# Required-Start:    
# Required-Stop:     
# Should-Start:      
# Should-Stop:       
# X-Start-Before:    $x-display-manager gdm kdm xdm wdm ldm sdm nodm
# X-Interactive:     true
# Default-Start:     
# Default-Stop:      0 1 2 3 4 5 6
# Short-Description: public functions for shell
# Descrioption:      These are public functions for shell.
#                    by using ../pffs to source it to current shell
#                     environment to call.
### END INIT INFO

### Original version by Leerkan
# <d.lrk@outlook.com>, edited by Leerkan
### Modified for [what] by [who] [<email address>]

setGlobalVariable(){
	### BEGIN INIT INFO
	# Provides:          pffs global variable
	# Required-Start:    
	# Required-Stop:     
	# Should-Start:      
	# Should-Stop:       
	# X-Start-Before:    $x-display-manager gdm kdm xdm wdm ldm sdm nodm
	# X-Interactive:     true
	# Default-Start:     
	# Default-Stop:      0 1 2 3 4 5 6
	# Short-Description: set pffs's global variable.
	# Descrioption:      set pffs's global variable. So all the scripts
	#                     can use it.
	### END INIT INFO

	### Original version by Leerkan
	# <d.lrk@outlook.com>, edited by Leerkan
	### Modified for [what] by [who] [<email address>]
	pffs_var_templateFolderName="template";
}
setGlobalVariable;
formatStringToReg(){
	### BEGIN INIT INFO
	# Provides:          format the string that will be send to RegExp.
	# Required-Start:    
	# Required-Stop:     
	# Should-Start:      
	# Should-Stop:       
	# X-Start-Before:    $x-display-manager gdm kdm xdm wdm ldm sdm nodm
	# X-Interactive:     true
	# Default-Start:     
	# Default-Stop:      0 1 2 3 4 5 6
	# Short-Description: format the string that will be send to RegExp.
	# Descrioption:      format the string that will be send to RegExp.
	#                    To make sure the RegExp will work well 
	### END INIT INFO

	### Original version by Leerkan
	# <d.lrk@outlook.com>, edited by Leerkan
	### Modified for [what] by [who] [<email address>]
	s="$1";
	#s=${s//\ /\\\ }
	s=${s//\//\\\/}
	s=${s//\"/\\\"}
	s=${s//\^/\\\^}
	s=${s//\$/\\\$}
	echo -n "${s}"
}

ifYesDo(){
	### BEGIN INIT INFO
	# Provides:          Ask Before Processing Interative Service.
	# Required-Start:    
	# Required-Stop:     
	# Should-Start:      
	# Should-Stop:       
	# X-Start-Before:    $x-display-manager gdm kdm xdm wdm ldm sdm nodm
	# X-Interactive:     true
	# Default-Start:     
	# Default-Stop:      0 1 2 3 4 5 6
	# Short-Description: Ask Before Processing Interative Service.
	# Descrioption:      Ask Before Processing Interative Service.
	#                    ifYesDo "echo abc" will ask before eval "echo abc".
	#                    with an answer q , the script will be executed quietly.
	#                    or you can give the q to the second argument.eg. ifYesDo "echo abc" q.
	#                    with a third argument to call ifYesDo,
	#                     it will ask with the 3rd argument instead of the 1st argument,
	#                     which will be executed.
	#                    eg. ifYesDo "echo Hello World" "" "Do you want to echo hello world?" ;
	#                    With a forth argument to call ifYesDo,
	#                     it will provide more explanation, if user choose "m".
	#                   eg.  ifYesDo "catIntoFile $'\n	TCPKeepAlive yes\n	ServerAliveInterval 120' /etc/ssh/ssh_config" "" "set the ssh connection keeping alive." "To avoid to be disconnected, if the client not active for a short time."; #set the ssh connection keeping alive.;
	### END INIT INFO

	### Original version by Leerkan
	# <d.lrk@outlook.com>, edited by Leerkan
	### Modified for [what] by [who] [<email address>]
	local script=${1};
	local defaultAnswer=${2}
	local explanation=${3};
	local moreExplanation=${4};
	local messageOfPlsChoose="press 'yes' or 'no'. for more info, try [s/e/m]:";
	case "${explanation}" in
		"") echo -n "${script}" "[y/n]:" ;;
		*) echo -n "${explanation}" "[y/n]:" ;;
	esac
	case ${defaultAnswer} in
		y|Y|yes|Yes|q|Q|quiet|QUIET|n|N|no|NO) in=${defaultAnswer};
			echo ${in};;
		m|M|more|MORE) in=${defaultAnswer};
			echo ${in};;
		*) while read in ;do 
			case "${in}" in
				y|Y|yes|Yes|q|Q|quiet|QUIET|n|N|no|NO) break ;;
				s|S|script|Script) echo " "${script}; echo -n " "${messageOfPlsChoose} ;;
				e|E|explanation|Explanation) echo " "${explanation}; echo -n " "${messageOfPlsChoose} ;;
				m|M|more|More|MoreExplanation) echo " "${moreExplanation}; echo -n " "${messageOfPlsChoose} ;;
				*) echo -n " "${messageOfPlsChoose} ;;
			esac
		done;
	esac
	case "${in}" in
		y|Y|yes|Yes) eval "${script}" ;;
		q|Q|quiet|QUIET) eval "${script}" > /dev/null;;
		n|N|no|NO) echo "fine, passed." ;;
	esac
}

readNonBlankValue(){
	### BEGIN INIT INFO
	# Provides:         Read Non-blank Value. 
	# Required-Start:    
	# Required-Stop:     
	# Should-Start:      
	# Should-Stop:       
	# X-Start-Before:    $x-display-manager gdm kdm xdm wdm ldm sdm nodm
	# X-Interactive:     true
	# Default-Start:     
	# Default-Stop:      0 1 2 3 4 5 6
	# Short-Description: Ask Before Processing Interative Service.
	# Descrioption:      Ask Before Processing Interative Service.
	#                    EXAMPLE:
	#                    read non blank value into the second parameter
	#                     which is given as 'country' here.
	#                     The default value is US;
	#                        readNonBlankValue "KEY_CONTURY=" country "US";
	#                    If there's default value.
	#                    Then default value will be taken.
	### END INIT INFO

	### Original version by Leerkan
	# <d.lrk@outlook.com>, edited by Leerkan
	### Modified for [what] by [who] [<email address>]
	local question=${1} ;
	local answer=${2} ;
	local defaultAnswer=${3} ;
	local echooff=${4} ;
	local in ;
	if [[ "${answer}" ]] ; then
		echo -n "${question}" ;
		if [[ "${echooff}" ]] ; then
			stty -echo;
		fi;
		while read in ;do 
			if [[ "${echooff}" ]] ; then
				stty echo;
			fi;
			case "${in}" in
				"") if [[ "${defaultAnswer}" ]] ; then
						eval ${answer}="'${defaultAnswer}'" ;
						break;
					else
						echo "";
						echo "# Don't leave this field blank. " "${question}"; 
						if [[ "${echooff}" ]] ; then
							stty -echo;
						fi;
						continue;
					fi ;;
				*) eval ${answer}="'${in}'" ;
					break ;;
			esac
			if [[ "${echooff}" ]] ; then
				stty -echo;
			fi;
		done;
		if [[ "${echooff}" ]] ; then
			stty echo;
		fi;
	else
		echo "" ;
	fi;
}

preDealDir(){
	### BEGIN INIT INFO
	# Provides:         pre-deal the string of directory. 
	# Required-Start:    
	# Required-Stop:     
	# Should-Start:      
	# Should-Stop:       
	# X-Start-Before:    $x-display-manager gdm kdm xdm wdm ldm sdm nodm
	# X-Interactive:     true
	# Default-Start:     
	# Default-Stop:      0 1 2 3 4 5 6
	# Short-Description: pre-deal the string of directory.
	# Descrioption:      pre-deal the string of directory.
	#                    resolve links - $0 may be a softlink
	### END INIT INFO

	### Original version by Hugo
	# <photography.hugohallman.com>, edited by Leerkan
	### Modified for [what] by [who] [<email address>]
	PRG="$0"
	while [ -h "$PRG" ] ; do
	  ls=`ls -ld "$PRG"`
	  link=`expr "$ls" : '.*-> \(.*\)$'`
	  if expr "$link" : '/.*' > /dev/null; then
		PRG="$link"
	  else
		PRG=`dirname "$PRG"`/"$link"
	  fi
	done
	PRGDIR=`dirname "$PRG"`
	echo ${PRGDIR}
}

mustBeExist(){
	# make sure it is exist.
	local fileDir=${1};
	if [ ! -e ${fileDir} ];
	then
		touch ${fileDir};
	fi;
}
catIntoFile(){
	#cat sentences into file
	local sentences=${1};
	local fileDir=${2};
	local eof="EOF";
	case ${3} in
		"") eof="EOF";;
		*) eof=${3};;
	esac;
	mustBeExist ${fileDir};
	if [ -w ${fileDir} ];
	then
		cat >>${fileDir}<<-${eof}
			${sentences}
			${eof}
	else
		echo ${fileDir} can not be wrote!
	fi;
}

sedIntoFile(){
	#sed sentences after specified words in specified file.
	#EXAMPLE:
	# replace a string in file.
	#	local refSentence="export KEY_CITY=\"NY\"";
	#	local sentences="export KEY_CITY=\"CD\"";
	#	local fileDir="/home/will/tmp/testfile";
	#	echo "${refSentence}" > ${fileDir};
	#	sedIntoFile ${sentences} ${fileDir} replace "export KEY_CITY=.*" 
	#
	local sentences=${1};
	local fileDir=${2};
	local sedType=${3};
	local refSentence=${4};
#echo "$refSentence";
	mustBeExist ${fileDir};
	if [ -w ${fileDir} ];
	then
		if [ $# -lt 2 ];
		then
			return 2;
		elif [ $# -lt 4 ];
		then # add sentences to the end of the file;
			case ${sedType} in
				""|a|after|AFTER) sed -i -e $"$ a ${sentences}" ${fileDir} ;;
				b|before|BEFORE) sed -i -e $"$ i ${sentences}" ${fileDir} ;;
				r|replace|REPLACE) sed -i -e $"/^.*$/ d" ${fileDir}&&echo ${sentences} > ${fileDir} ;;
				*) return 2 ;;
			esac
		elif [ $# -ge 4 ];
		then
			case ${sedType} in
				""|a|after|AFTER) sed -i -e $"/^${refSentence}$/ a ${sentences}" ${fileDir} ;;
				b|before|BEFORE) sed -i -e $"/^${refSentence}$/ i ${sentences}" ${fileDir} ;;
				r|replace|REPLACE) sed -i -e $"/^${refSentence}$/ c ${sentences}" ${fileDir} ;;
				*) return 2 ;;
			esac
		else
			return 2 ;
		fi
	else
		echo ${fileDir} can not be wrote!
	fi
}
